﻿function InitTree(TreeObject, ErrorModal, InputSavedSelectedNodeID, UpdateID) {
    InputSavedSelectedNodeID.val("no_nodes_are_selected");
    TreeObject.children().remove();
    var idate = new Date();
    var divid = "tempjstree" + idate.toLocaleTimeString();
    divid = divid.replace(/:/g, "T");
    var divstr = "<div id=\"" + divid + "\"><div>"
    TreeObject.append(divstr);
    var tempid = $("#" + divid);
    tempid.jstree({
        "core": {
            'data': function (node, callback) {
                $.ajax(
                    {
                        url: "/Service/Data/GetListData.ashx",
                        type: "post",
                        dataType: "json",
                        data: {
                            "entityname": "BusinessUnit",
                            "pagesize": "1000000",
                            "filter": JSON.stringify(GenerateFilter(node.id))
                        },
                        success: function (data, textStatus) {
                            callback.call(this, JSONProcessor(data.List, UpdateID, node));
                        },
                        error: function (data, textStatus) {
                            ErrorModal.modal('show');
                        }
                    }
                );

            }
        },
        'strings': {
            'Loading ...': '加载中...'
        },
        'multiple': false
    })
        .on('select_node.jstree', function (node, selected) {
            InputSavedSelectedNodeID.val(selected.node.id);
            core.View.SearchForBus("ListInnerContainer", selected.node.id);
            $("#ListInnerContainer").css("display", "block");
        })
    .on('deselect_node.jstree', function (node, selected) {
        if (InputSavedSelectedNodeID.val() == selected.node.id) InputSavedSelectedNodeID.val('no_node_are_selected');
    })
}//在传入DIV之下创建临时DIV后在临时DIV创建来自固定接口的树
//这棵树在加载孩子只有一个时会自动打开 这个孩子的子节点 
//传入用于存储当前选择ID的INPUT 
//存在传入的ID时将该ID对应节点置为DISABLE，其孩子节点递归为DISABLE（不传入（null）ID全树无Disable)
//绑定一个显示网络错误的模态框在网络错误时显示

function GetNowSelectedTreeNodeID(InputSavedSelectedNodeID) {
    if (InputSavedSelectedNodeID.val() == 'no_nodes_are_selected' || InputSavedSelectedNodeID.val() == '') return null;
    else return InputSavedSelectedNodeID.val();
}//传入存储ID的INPUT转换为真实ID，针对当前情况作出对应处理

function NewButtonClicked() {
    window.open("/Pages/DataPages/Form/FormPage.aspx?entityname=businessunit");
}//新建按钮动作

function EditButtonClicked(InputSavedSelectedNodeID) {
    if (GetNowSelectedTreeNodeID(InputSavedSelectedNodeID) == null) return;
    window.open("/Pages/DataPages/Form/FormPage.aspx?entityname=businessunit&id=" + GetNowSelectedTreeNodeID(InputSavedSelectedNodeID));
}//编辑按钮动作

function EditPreBusinessUnitButtonClicked(InputSavedSelectedNodeID, UpdateJSTreeView, UpdateView, ErrorModel, UpdateIDInput, PreBusinessUnitIDInput) {
    if (GetNowSelectedTreeNodeID(InputSavedSelectedNodeID) == null) return;
    GenerateUpdateView(GetNowSelectedTreeNodeID(InputSavedSelectedNodeID), UpdateJSTreeView, UpdateView, ErrorModel, UpdateIDInput, PreBusinessUnitIDInput);
}//修改上级部门的（打开模态框）

function GenerateUpdateView(UpdateID, UpdateJSTreeView, UpdateView, ErrorModel, UpdateIDInput, PreBusinessUnitIDInput) {
    UpdateIDInput.val(UpdateID);
    PreBusinessUnitIDInput.val("no_nodes_are_selected");
    InitTree(UpdateJSTreeView, ErrorModel, PreBusinessUnitIDInput, UpdateID);
    //显示更新上级部门框 防止误触关闭单击背景隐藏模态框
    UpdateView.modal({ backdrop: false });
}//创建模态框中的JSTREE

function ConfirmUpdatePreBusinessUnit(InputSavedSelectedNodeID, InputSavedTargetID, MainJSTree, INGModal, ErrorModal, MainSelectNode) {
    if (GetNowSelectedTreeNodeID(InputSavedSelectedNodeID) == null || GetNowSelectedTreeNodeID(InputSavedTargetID) == null) return;
    var JSONDataObject = {};
    JSONDataObject["BusinessUnitId"] = GetNowSelectedTreeNodeID(InputSavedTargetID);
    JSONDataObject["PreBusinessUnit"] = GetNowSelectedTreeNodeID(InputSavedSelectedNodeID);
    //修改中提示框显示
    INGModal.modal({ backdrop: 'static', keyboard: false });
    /*调用接口修改上级部门*/
    $.ajax(
    {
        url: "/Service/Privilege/UpdateBusinessUnit.ashx",
        type: "post",
        dataType: "json",
        data: {
            "OperationTypeCode": "UpdatePreBusinessUnit",
            "BusinessUnit": JSON.stringify(JSONDataObject)
        },
        success: function (data, textStatus) {
            INGModal.modal('hide');//隐藏修改中提示框
            InitTree(MainJSTree, ErrorModal, MainSelectNode, 0, null);//刷新树
        },
        error: function (data, textStatus) {
            INGModal.modal('hide');
            ErrorModal.modal('toggle')
        }
    }
    );
}//确认修改按钮操作

function JSONProcessor(JSONDataFromServer, id, parent) {
    var JSONDataForJSTree = [];
    for (var temp = 0; temp < JSONDataFromServer.length; temp++) {
        var NodeObj = {};
        NodeObj["text"] = JSONDataFromServer[temp].name;
        NodeObj["id"] = JSONDataFromServer[temp].businessunitid;
        NodeObj["children"] = true;
        NodeObj["state"] = { "opened": false };
        if (JSONDataFromServer.length <= 1) NodeObj["state"] = { "opened": true }
        if (id != null && (JSONDataFromServer[temp].businessunitid == id || parent.state.disabled)) {
            NodeObj["state"] = { "opened": false, "disabled": true }
        }
        JSONDataForJSTree.push(NodeObj);
    }
    return JSONDataForJSTree;
} //JSON翻译方法，处理JSON数据不标准

function GenerateFilter(id) {
    var condition_json_Node = { "Conditions": [{ "AttributeName": "prebusinessunit" }], "FilterOperator": "and", "Filters": [] };
    if (id == null || id == '#') {
        condition_json_Node.Conditions[0]["Operator"] = "Null";
    }
    else {
        var IDNode = {}
        IDNode["ID"] = id;
        condition_json_Node.Conditions[0]["Operator"] = "Equal";
        condition_json_Node.Conditions[0]["Values"] = [];
        condition_json_Node.Conditions[0]["Values"].push(IDNode);
    }
    return condition_json_Node;
}//创建FilterJson字符串用于筛选

function DeleteButtonClicked(InputSavedSelectedNodeID, INGModal, MainJSTree, ErrorModal, MainSelectNode) {
    if (GetNowSelectedTreeNodeID(InputSavedSelectedNodeID) == null) return;
    var JSONDataObject = {};
    JSONDataObject["BusinessUnitId"] = GetNowSelectedTreeNodeID(InputSavedSelectedNodeID);
    INGModal.modal({ backdrop: 'static', keyboard: false });
    $.ajax(
{
    url: "/Service/Privilege/UpdateBusinessUnit.ashx",
    type: "post",
    dataType: "json",
    data: {
        "OperationTypeCode": "DeleteBusinessUnit",
        "BusinessUnit": JSON.stringify(JSONDataObject)
    },
    success: function (data, textStatus) {
        INGModal.modal('hide');//隐藏修改中提示框
        InitTree(MainJSTree, ErrorModal, MainSelectNode, 0, null);//刷新树
    },
    error: function (data, textStatus) {
        INGModal.modal('hide');
        ErrorModal.modal('toggle')
    }
}
);
}

//业务部门页面根据业务部门获取对应的用户
core.View.SearchForBus = function (id, value) {
    var searchValue = value;
    core.View.SearchFilter[id] = {};
    core.View.SearchFilter[id]["Conditions"] = [];
    core.View.SearchFilter[id]["FilterOperator"] = "OR";
    core.View.FilterData[id]["Filters"] = [];

    for (var i = 0; i < core.View.FilterData[id]["Conditions"].length; i++) {
        if (core.View.FilterData[id]["Conditions"][i]["AttributeName"] == "businessunitid") {
            core.View.FilterData[id]["Conditions"].splice(i, 1)
        }
    }

    var ConditionExpression = {};
    ConditionExpression["AttributeName"] = "businessunitid";
    ConditionExpression["Operator"] = "equal";
    var lookup = {};
    lookup["Name"] = null;
    lookup["id"] = searchValue;
    ConditionExpression["Values"] = [lookup];
    core.View.FilterData[id]["Conditions"].push(ConditionExpression);


    var order = String.format("{0} {1} ", core.View.Orderby[id].att, core.View.Orderby[id].value);

    core.View.GetListData(core.EntityName[id], JSON.stringify(core.View.FilterData[id]), id,0,1000);
}

function ShowUnderConstracted() {
    alert("开发中");
}//开发中返回



